package com.samphanie.security.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import com.samphanie.common.constants.SystemConstants;
import com.samphanie.common.enums.ResultCode;
import com.samphanie.common.execetion.ApiException;
import com.samphanie.common.utils.RequestHolder;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZSY
 * @email 1451691457@qq.com
 */
public class JwtUtils {

    public static JSONObject getJwtPayload() {
        String token = RequestHolder.getHttpServletRequestHeader(SystemConstants.JWT_TOKEN_HEADER);
        // 从token中解析用户信息并设置到Header中去
        String realToken = token.replace(SystemConstants.JWT_TOKEN_PREFIX, "");
        JWSObject jwsObject = null;
        try {
            jwsObject = JWSObject.parse(realToken);
        } catch (ParseException e) {
            throw new ApiException(ResultCode.USER_ERROR_A0340);
        }
        String payload = jwsObject.getPayload().toString();
        return JSONUtil.parseObj(payload);
    }

    public static Long getUserId() {
        return getJwtPayload().getLong("id");
    }

    public static String getUsername() {
        return getJwtPayload().getStr("username");
    }

    public static Long getExp() {
        return getJwtPayload().getLong("exp");
    }

    public static String getJti() {
        return getJwtPayload().getStr("jti");
    }

    public static String getClient() {
        return getJwtPayload().getStr("client_id");
    }

    public static List<String> getRoles() {
        JSONObject payload = getJwtPayload();
        if (payload != null && payload.size() > 0) {
            List<String> list = payload.get(SystemConstants.AUTHORITY_CLAIM_NAME, List.class);
            return new ArrayList<>(list);
        }
        return null;
    }

}
